package com.yl.immodule.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.camera.base.v.BaseFragment;
import com.camera.routemodule.RouterPath;
import com.yl.immodule.R;
import com.yl.immodule.adapter.ChannelClickListener;
import com.yl.immodule.adapter.ChannelListAdapter;
import com.yl.immodule.bean.YChannel;
import com.yl.immodule.databinding.HomeFragmentChannellistBinding;
import com.yl.immodule.fragment.model.ChannelListViewModel;
import com.yl.immodule.func.AddChannelFunc;
import com.yl.immodule.widget.InterceptViewPager;
import com.android.yl.ylicpsdk.ICPRtcEventHandler;
import com.unionbroad.greendao.Channel;
import com.unionbroad.app.PocApplication;

import java.util.ArrayList;
import java.util.List;

/**
 * 频道类型: Channel.getChannelType()
 * "4"：语音对讲组
 * <p>
 * ----------------其它类型暂时不支持------------------
 * "1"：视频对讲
 * "2"：语音会议
 * "5"：视频会议
 */
@Route(path = RouterPath.path.channel_fragment)
public class ChannelListFragment extends BaseFragment<HomeFragmentChannellistBinding> implements ChannelClickListener {
    private final String TAG = ChannelListFragment.class.getSimpleName();
    private ChannelListAdapter adapter;
    private InterceptViewPager homeViewPager;
    private ChannelListViewModel viewModel;

    public ChannelListFragment() {
    }

    public static ChannelListFragment newInstance() {
        return new ChannelListFragment();
    }

    public void bindViewPager(InterceptViewPager viewPager) {
        homeViewPager = viewPager;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ChannelListViewModel.class);
    }

    public void startAddChannel() {
        AddChannelFunc addChannelFunc = new AddChannelFunc(this.getContext());
        addChannelFunc.start();
    }

    @Override
    public void loadData(boolean isRefresh) {
        // 当页面加载或刷新时，可以在这里重新获取数据
        if (isRefresh) {
            viewModel.refreshChannels();
        }
    }

    @Override
    public void initView() {
        // 设置ViewModel到binding
        getMBinding().setViewModel(viewModel);
        
        getMBinding().listview.setLayoutManager(new LinearLayoutManager(getContext()));
        // 创建适配器并传入点击监听器(this)
        adapter = new ChannelListAdapter(this,viewModel);
        getMBinding().listview.setAdapter(adapter);

        // 设置下拉刷新
        getMBinding().swipeRefreshLayout.setOnRefreshListener(() -> viewModel.refreshChannels());
        
        // 设置刷新时的颜色变化
        getMBinding().swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
                
        // 观察频道数据变化
        viewModel.channels.observe(getViewLifecycleOwner(), channels -> {
            adapter.submitList(channels);
        });
        
        // 观察加载状态
        viewModel.isLoading.observe(getViewLifecycleOwner(), isLoading -> {
            getMBinding().swipeRefreshLayout.setRefreshing(isLoading);
        });

        viewModel.currentChannel.observe(getViewLifecycleOwner(), channel -> {
            adapter.toTopChannel(channel);
        });
        viewModel.showAddChannelDialog.observe(getViewLifecycleOwner(), aBoolean -> {
            if (aBoolean) {
                startAddChannel();
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.home_fragment_channellist;
    }

    /**
     * 实现ChannelClickListener接口的方法
     */
    @Override
    public void onChannelClick(YChannel channel) {
        // 处理频道点击事件
        final List<String> items = new ArrayList<>();
        if (TextUtils.equals(PocApplication.sUserNumber + "", channel.getChannel().getCreateType())) {
            items.add("删除群组");
        }
        if (ICPRtcEventHandler.ChannelType.AUDIO_PTT.equals(channel.getChannel().getChannelType())) {
            items.add("进入群组");
        } else if (ICPRtcEventHandler.ChannelType.VIDEO_MEETING.equals(channel.getChannel().getChannelType())) {
            items.add("进入视频会议");
        } else if (ICPRtcEventHandler.ChannelType.AUDIO_MEETING.equals(channel.getChannel().getChannelType())) {
            items.add("进入语音会议");
        }
        
        new AlertDialog.Builder(getContext())
                .setItems(items.toArray(new String[0]), (dialogInterface, i) -> {
                    if ("进入群组".equals(items.get(i))) {
                        viewModel.joinChannel(channel.getChannel().getChannelNumber() + "");
                        if (homeViewPager != null) {
                            homeViewPager.setCurrentItem(0);
                        }
                    } else if ("删除群组".equals(items.get(i))) {
                        viewModel.removeAudioPTTChannel(channel);
                    } else if ("进入视频会议".equals(items.get(i))) {
                        viewModel.startVideoMeeting(getContext(), channel.getChannel().getChannelNumber() + "");
                    } else if ("进入语音会议".equals(items.get(i))) {
                        viewModel.startAudioMeeting(getContext(), channel.getChannel().getChannelNumber() + "");
                    }
                })
                .show();
    }

}
